package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.homeservicemanagementsystem.config.annotation.RestControllerMapping;
import com.heima.homeservicemanagementsystem.entity.SysUser;
import com.heima.homeservicemanagementsystem.entity.dto.RegisterDto;
import com.heima.homeservicemanagementsystem.entity.dto.UpdataPwdDto;
import com.heima.homeservicemanagementsystem.entity.vo.Login;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.module.ValidGroup;
import com.heima.homeservicemanagementsystem.service.SysUserService;
import com.heima.homeservicemanagementsystem.utils.PasswordUtils;
import com.heima.homeservicemanagementsystem.utils.RedisClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description
 * @Author jcf
 * @Date 2025/2/27
 */
@Tag(name = "用户登录退出")
@RestControllerMapping("/auth")
public class loginController {
    private static final Logger log = LoggerFactory.getLogger(loginController.class);
    @Resource
    private SysUserService sysUserService;
    @Resource
    private RedisClient redisClient;

    @SaIgnore
    @PostMapping("/login")
    @Operation(summary = "用户名登录")
    public Result<Map<String, String>> loginByUsernameAndPassword(@RequestBody Login login) {
//        log.info("用户的信息:{}", login);
//        log.info("是否有:{}", StringUtils.hasLength(login.getUsername()));
        if (StringUtils.hasLength(login.getUsername())) {
            SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, login.getUsername()));

            if (user == null) {
                return Result.error("账号或者密码错误");
            }
            log.info("获取的用户信息：{}", user);
            String password = login.getPassword();
            String salt = user.getSlat();
            String s = PasswordUtils.decryptStr(salt, user.getPassword());
            log.info("登录密码：{}，数据库密码：{}", password, s);
            if (password.equals(s)) {
                return getMapResult(user);
            }
        } else if (StringUtils.hasLength(login.getEmail())) {
            log.info("登录邮箱：{}", login.getEmail());
            SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getEmail, login.getEmail()));

            if (!Objects.isNull(user)) {
                String password = login.getPassword();
                String salt = user.getSlat();
                String s = PasswordUtils.decryptStr(salt, user.getPassword());
                if (password.equals(s)) {
                    return getMapResult(user);
                }
                return Result.error("邮箱或密码错误");
            }
            return Result.error("邮箱或密码错误");

        } else {
//            log.info("登录手机号：{}", login.getMobile());
            String key = "mobileCode-" + login.getMobile();
            String s = redisClient.get(key);
//            log.info("验证码：{}", login.getCaptcha());
            boolean equals = login.getCaptcha().equals(s);
//            log.info("相等+：{}", equals);
//            log.info("相等-：{}", StringUtils.hasLength(login.getCaptcha()));
            if (!StringUtils.hasLength(login.getCaptcha()) || !equals) {
                return Result.error(500, "验证码错误,请重新获取");
            } else {
//                log.info("验证码成功");
                SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getPhone, login.getMobile()));
                if (!Objects.isNull(user)) {
                    return getMapResult(user);
                }
//                return Result.success();
            }
            return Result.error(500, "验证码错误,请重新获取");
        }

        return Result.error("其他未知错误");


    }

    private static Result<Map<String, String>> getMapResult(SysUser user) {
        StpUtil.login(user.getId(), "pc");
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        Map<String, String> map = new HashMap<>(2);
        map.put("tokenHead", tokenInfo.tokenName);
        map.put("token", tokenInfo.tokenValue);
        return Result.success(map);
    }

    @SaIgnore
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result loginByUsernameAndPassword(@RequestBody RegisterDto registerDto) {

        return sysUserService.register(registerDto);


    }

    @SaIgnore
    @PostMapping("/updatepassword")
    @Operation(summary = "用户重置密码")
    public Result repassword(@RequestBody UpdataPwdDto updataPwdDto) {

        return sysUserService.updataPwd(updataPwdDto);

    }

    @SaIgnore
    @GetMapping("logout")
    @Operation(summary = "退出登录")
    public Result<Boolean> logout() {
        StpUtil.logout();
        return Result.success();
    }

    @GetMapping("test")
    @SaCheckPermission("login:test")
    public Result<String> test() {
        return Result.success();
    }

}